<template>
  <div class="spare-picker">
    <!-- 备件类型 -->
    <el-form-item label="备件类型" :prop="propPrefix + 'spareType'">
      <el-radio-group v-model="innerSpareType" @change="onTypeChange">
        <el-radio :label="SPARE_MODE.NORMAL_SELECT">普通</el-radio>
        <el-radio :label="SPARE_MODE.SPECIAL_PURCHASE">特殊</el-radio>
      </el-radio-group>
    </el-form-item>

    <!-- 普通模式 -->
    <template v-if="isNormalMode">
      <el-form-item label="选择备件">
        <el-select
          v-model="pickedIds"
          multiple filterable clearable collapse-tags collapse-tags-tooltip
          placeholder="选择需要的普通备件（可多选）"
          style="width: 100%"
          @change="syncPickedToSpares"
        >
          <el-option
            v-for="op in spareOptionsNormal"
            :key="op.value"
            :label="op.label"
            :value="op.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="备件清单">
        <el-table
          :data="innerSpares"
          border size="small" :height="tableHeight" style="width:100%"
          empty-text="请先选择普通备件"
        >
          <el-table-column label="备件名称" min-width="160">
            <template #default="{ row }">{{ id2name(row.spareId, 0) }}</template>
          </el-table-column>
          <el-table-column label="数量" min-width="160" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.qty" :min="1" :step="1" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="{ row }">
              <el-button link type="danger" size="small" @click="removeSpare(row.spareId)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </template>

    <!-- 特殊采购模式 -->
    <template v-else>
      <div class="classPur">
        <el-divider content-position="left">备件采购清单</el-divider>

        <!-- 选择已有特殊备件 -->
        <el-form-item label="从备件库选择">
          <el-select
            v-model="selectedExistingIds"
            multiple
            filterable
            clearable
            collapse-tags
            placeholder="选择已有特殊备件"
            style="width: 100%"
            @change="addExistingSparesToPurchase"
          >
            <el-option
              v-for="op in spareOptionsSpecial"
              :key="op.value"
              :label="op.label"
              :value="op.value"
            />
          </el-select>
        </el-form-item>

        <div class="special-toolbar">
          <el-button type="primary" plain @click="addSpecialRow()">新增一行</el-button>
          <el-text type="info">可录入或选择已有备件，编码仅允许 A-Z / 0-9 / - / _。</el-text>
        </div>

        <el-table
          :data="innerSpecialItems"
          border stripe size="small"
          :height="tableHeight"
          class="special-table"
          empty-text="请通过上方选择已有备件或点击新增添加条目"
        >
          <el-table-column label="备件名称" min-width="100">
            <template #default="{ row }">
              <el-input v-model="row.name" placeholder="请输入备件名称"/>
            </template>
          </el-table-column>
          <el-table-column label="编码" min-width="100">
            <template #default="{ row }">
              <el-input v-model="row.code" maxlength="64" placeholder="仅字母/数字/-/_" @input="enforceCode(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="数量" min-width="100" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.qty" :min="1" :step="1" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="采购周期(天)" min-width="100" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.orderDate" :min="1" :step="1" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="{ row, $index }">
              <el-button link type="primary" size="small" @click="copySpecialRow(row, $index)">复制</el-button>
              <el-button link type="danger" size="small" @click="removeSpecialRow($index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { listSpare } from '@/api/sbtz/spare'
import { SPARE_MODE } from '@/constants/spare.const'

// props
const props = defineProps({
  spareType: { type: Number, default: SPARE_MODE.NORMAL_SELECT },
  spares: { type: Array, default: () => [] },
  specialItems: { type: Array, default: () => [] },
  tableHeight: { type: [Number, String], default: 200 },
  propPrefix: { type: String, default: '' }
})
const emit = defineEmits(['update:spareType','update:spares','update:specialItems'])

// 内部数据
const innerSpareType = ref(props.spareType)
const innerSpares = ref(Array.isArray(props.spares) ? [...props.spares] : [])
const innerSpecialItems = ref([])

// 下拉选项缓存
const spareOptionsNormal = ref([])   // type = 0
const spareOptionsSpecial = ref([])  // type = 1

// 初始化加载所有备件
async function loadSpareOptions() {
  const res = await listSpare({ pageNum: 1, pageSize: 9999 })
  const rows = res?.rows ?? res?.data ?? []
  spareOptionsNormal.value = rows
    .filter(r => Number(r.type) === 0)
    .map(r => ({
      value: r.id,
      label: r.name,
      code: r.code,
      qty: r.stock_total ?? r.qty ?? 1,
      orderDate: r.order_date ?? r.orderDate ?? 1
    }))

  spareOptionsSpecial.value = rows
    .filter(r => Number(r.type) === 1)
    .map(r => ({
      value: r.id,
      label: r.name,
      code: r.code,
      qty: r.stock_total ?? r.qty ?? 1,
      orderDate: r.order_date ?? r.orderDate ?? 1
    }))
}

// 初始化加载
onMounted(async () => {
  await loadSpareOptions()

  // ✅ 若是编辑模式（父组件有数据）
  if (props.spareType === SPARE_MODE.SPECIAL_PURCHASE && props.specialItems?.length) {
    innerSpareType.value = SPARE_MODE.SPECIAL_PURCHASE
    innerSpecialItems.value = [...props.specialItems]   // ← 加载已有特殊采购列表
  } else if (props.spareType === SPARE_MODE.NORMAL_SELECT && props.spares?.length) {
    innerSpareType.value = SPARE_MODE.NORMAL_SELECT
    innerSpares.value = [...props.spares]
  }
})

// ✅ 监听父组件 prop 更新（动态编辑时也能回显）
watch(
  () => props.specialItems,
  (v) => {
    if (innerSpareType.value === SPARE_MODE.SPECIAL_PURCHASE && Array.isArray(v)) {
      innerSpecialItems.value = [...v]
    }
  },
  { deep: true, immediate: true }
)

// ===== 普通模式逻辑 =====
const pickedIds = ref([])
const isNormalMode = computed(() => innerSpareType.value === SPARE_MODE.NORMAL_SELECT)

function id2name(id, type = 0) {
  const list = type === 1 ? spareOptionsSpecial.value : spareOptionsNormal.value
  return list.find(x => x.value === id)?.label || id
}

function syncPickedToSpares() {
  const set = new Set(pickedIds.value)
  innerSpares.value = innerSpares.value.filter(it => set.has(it.spareId))
  for (const id of set) {
    if (!innerSpares.value.some(it => it.spareId === id)) {
      innerSpares.value.push({ spareId: id, qty: 1 })
    }
  }
  emit('update:spares', innerSpares.value)
}

function removeSpare(id) {
  innerSpares.value = innerSpares.value.filter(it => it.spareId !== id)
  pickedIds.value = pickedIds.value.filter(i => i !== id)
  emit('update:spares', innerSpares.value)
}

// ===== 特殊采购模式逻辑 =====
const selectedExistingIds = ref([])

async function addExistingSparesToPurchase() {
  const selected = spareOptionsSpecial.value.filter(x => selectedExistingIds.value.includes(x.value))
  for (const item of selected) {
    // 从已有的 innerSpecialItems 中检查是否已存在
    if (!innerSpecialItems.value.some(i => i.code === item.code)) {
      innerSpecialItems.value.push({
        name: item.label,
        code: item.code?.toUpperCase() || '',
        qty: Number(item.stock_total || item.qty || 1),    // ✅ 优先取后端提供的库存数量
        orderDate: Number(item.order_date || item.orderDate || 1) // ✅ 优先取后端的采购周期
      })
    }
  }
  emit('update:specialItems', innerSpecialItems.value)
}


function addSpecialRow() {
  innerSpecialItems.value.push({ name: '', code: '', qty: 1, orderDate: 1 })
  emit('update:specialItems', innerSpecialItems.value)
}
function copySpecialRow(row, i) {
  innerSpecialItems.value.splice(i + 1, 0, { ...row })
  emit('update:specialItems', innerSpecialItems.value)
}
function removeSpecialRow(i) {
  const removed = innerSpecialItems.value[i]

  // 从表格中删除
  innerSpecialItems.value.splice(i, 1)

  // ✅ 如果上方下拉中选了这个备件，也同步移除
  if (removed?.code) {
    const matched = spareOptionsSpecial.value.find(
      (x) => x.code?.toUpperCase() === removed.code?.toUpperCase()
    )
    if (matched) {
      selectedExistingIds.value = selectedExistingIds.value.filter(
        (id) => id !== matched.value
      )
    }
  }

  emit('update:specialItems', innerSpecialItems.value)
}

function enforceCode(row) {
  row.code = (row.code || '').toUpperCase().replace(/[^A-Z0-9\-_]/g, '')
}

// ===== 切换逻辑 =====
function onTypeChange() {
  emit('update:spareType', innerSpareType.value)
  if (innerSpareType.value === SPARE_MODE.SPECIAL_PURCHASE) {
    innerSpares.value = []
    pickedIds.value = []
    innerSpecialItems.value = [] // 默认空
  } else {
    innerSpecialItems.value = []
    selectedExistingIds.value = []
  }
}
</script>

<style scoped>
.special-toolbar{ display:flex; align-items:center; gap:10px; margin-bottom:8px; }
.classPur{ margin-left:40px; }
</style>
